package main

import (
	"fmt"
	"gorm.io/gorm"
	"time"
)

// 设备
type LRDevice struct {
	gorm.Model

	Imei          string   `gorm:"uniqueIndex"`
	DeviceModelId uint     `gorm:"not null"` //外键 型号
	FuncStr       string   //功能配置字符串 如果为空 默认使用型号的功能配置
	BindUsers     []LRUser `gorm:"many2many:lruser_device_binds"`
}

// 用户
type LRUser struct {
	gorm.Model
	Email    string `gorm:"index"`
	Phone    string `gorm:"index"`
	Password string
	Admin    uint //是否为管理员  0 普通用户  1公司  2超级管理

}

// 绑定关系
type LRUserDeviceBind struct {
	Device       LRDevice `gorm:"foreignKey:LRDeviceID"`
	User         LRUser   `gorm:"foreignKey:LRUserID"`
	LRDeviceID   uint     `gorm:"primaryKey"`
	LRUserID     uint     `gorm:"primaryKey"`
	RelationName string   //绑定关系
	IsAdmin      uint     //是否为主管理员
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func ManyToManySample() {

	GLOBAL_DB.SetupJoinTable(&LRDevice{}, "BindUsers", &LRUserDeviceBind{})
	GLOBAL_DB.AutoMigrate(&LRDevice{}, &LRUser{}, &LRUserDeviceBind{})
	SomeSample()
}

func SomeSample() {

	/*GLOBAL_DB.Create(&LRUser{Phone: "12345"})
	GLOBAL_DB.Create(&LRUser{Phone: "4444444"})
	GLOBAL_DB.Create(&LRUser{Phone: "555555"})
	GLOBAL_DB.Create(&LRUser{Phone: "99999", Email: "123124@qq.com"})*/
	/*GLOBAL_DB.Create(&LRDevice{Imei: "111111"})
	GLOBAL_DB.Create(&LRDevice{Imei: "222222"})
	GLOBAL_DB.Create(&LRDevice{Imei: "333333"})
	GLOBAL_DB.Create(&LRDevice{Imei: "44444444"})*/

	//创建并绑定
	/*	GLOBAL_DB.Create(&LRDevice{Imei: "555555",
		BindUsers: []LRUser{
			{
				Email: "8888@163.com",
			},
			{
				Email: "99999@163.com",
			},
		}})*/

	//常见并绑定已存在的

	/*	var users []LRUser
		GLOBAL_DB.Find(&users, "id < 4")
		GLOBAL_DB.Create(&LRDevice{Imei: "8888",
			BindUsers: users})*/

	/*	var bindRecords []LRUserDeviceBind
		GLOBAL_DB.Find(&bindRecords, &LRUserDeviceBind{
			LRDeviceID: 5,
		})
		fmt.Println("binds:", bindRecords)*/

	/*var adminBinder LRUserDeviceBind
	GLOBAL_DB.Take(&adminBinder, &LRUserDeviceBind{
		LRDeviceID: 5,
		IsAdmin:    1,
	})

	if adminBinder.LRUserID == 0 {
		println("no admin user")

	}*/

	/*	var adminBinder LRUserDeviceBind
		GLOBAL_DB.Take(&adminBinder, &LRUserDeviceBind{
			LRDeviceID: 5,
			LRUserID:   6,
			IsAdmin:    0,
		})

		adminBinder.IsAdmin = 1*/

	//GLOBAL_DB.Model(&adminBinder).Update("is_admin", 1)
	/*GLOBAL_DB.Model(&adminBinder).Updates(&LRUserDeviceBind{
		IsAdmin: 2,
	})*/

	//已经存在的增加绑定关系
	/*	var bindUsers []LRUser
		GLOBAL_DB.Find(&bindUsers, "ID > 4")

		var device1 LRDevice
		GLOBAL_DB.Take(&device1, 1)
		GLOBAL_DB.Model(&device1).Association("BindUsers").Append(bindUsers)*/

	//var device1 LRDevice
	//var apiDev APIDevice
	//GLOBAL_DB.Take(&device1, 1).Scan(&apiDev)

	//GLOBAL_DB.Preload("BindUsers").Take(&device1, 1)

	//fmt.Println("dev1:", device1)
	//fmt.Println("apiDev:", apiDev)

	var bindRecords []LRUserDeviceBind
	GLOBAL_DB.Preload("Device").Preload("User").Find(&bindRecords).Where(&LRUserDeviceBind{
		LRDeviceID: 1,
	})

	fmt.Println("find dev1 binds", bindRecords)

}
